package com.net.wanjian.networkhospitalmanager.activity.my;

import android.graphics.Color;
import android.graphics.drawable.PaintDrawable;
import android.support.v7.widget.LinearLayoutManager;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.net.wanjian.networkhospitalmanager.R;
import com.net.wanjian.networkhospitalmanager.activity.base.BaseActivity;
import com.net.wanjian.networkhospitalmanager.adapter.MessageListAdapter;
import com.net.wanjian.networkhospitalmanager.adapter.NotificationTypeAdapter;
import com.net.wanjian.networkhospitalmanager.adapter.base.RecyclerBaseAdapter;
import com.net.wanjian.networkhospitalmanager.bean.NotificationTypeLocalBean;
import com.net.wanjian.networkhospitalmanager.bean.SearchMessageListResult;
import com.net.wanjian.networkhospitalmanager.bean.SetMessageReadResult;
import com.net.wanjian.networkhospitalmanager.consts.AppConsts;
import com.net.wanjian.networkhospitalmanager.consts.ErrorCodeReturn;
import com.net.wanjian.networkhospitalmanager.net.HttpUtil;
import com.net.wanjian.networkhospitalmanager.netstatus.NetUtils;
import com.net.wanjian.networkhospitalmanager.utils.SharedXmlUtil;
import com.net.wanjian.networkhospitalmanager.utils.URLDecoderUtil;
import com.net.wanjian.networkhospitalmanager.view.LPopupWindow;
import com.net.wanjian.networkhospitalmanager.view.NoDataEmptyView;
import com.net.wanjian.networkhospitalmanager.widge.RefreshRecyclerView;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import io.reactivex.observers.DisposableObserver;

public class NotificationListActivity extends BaseActivity {

    private final String CURRENT_POSITION = "currentposition";


    @BindView(R.id.top_back_text_tv)
    TextView topBackTextTv;
    @BindView(R.id.top_back_layout)
    LinearLayout topBackLayout;
    @BindView(R.id.top_title_tv)
    TextView topTitleTv;
    @BindView(R.id.notification_list_all_info_layout)
    LinearLayout notificationListAllInfoLayout;
    @BindView(R.id.notification_list_recycler)
    RefreshRecyclerView notificationListRecycler;
    @BindView(R.id.top_title_tag_iv)
    ImageView topTitleTagIv;//图标切换，select
    @BindView(R.id.notification_top_layout)
    RelativeLayout notificationTopLayout;
    @BindView(R.id.teacher_event_progress)
    ProgressBar teacherEventProgress;
    @BindView(R.id.no_data_layout)
    NoDataEmptyView noDataLayout;
    private LPopupWindow mPopupWindow;

    private List<NotificationTypeLocalBean> typeList;
    private int currentNum = AppConsts.currentPageNum, currentPageNum, countNum;
    private List<SearchMessageListResult.DataBean.MessageListBean> mMessageList;
    private MessageListAdapter messageListAdapter;

    @Override
    protected void initData() {

        initLocalTypeData();

        topBackLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                NotificationListActivity.this.finish();
            }
        });

        notificationListAllInfoLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                //弹出菜单
                showMenu();
            }
        });

        noDataLayout.setNoData(R.string.no_notification_text);
        noDataLayout.setOnReLoadClickListener(new NoDataEmptyView.OnReLoadClickListener() {
            @Override
            public void onReloadClick(View v) {
                //获取当前选择的类型
                int position = SharedXmlUtil.getInstance().read(CURRENT_POSITION, 0);
                handleResult(typeList.get(position).getMessageType(),typeList.get(position).getTypeName());
            }
        });
        notificationListRecycler.setEmptyView(noDataLayout);
        notificationListRecycler.setRefreshMode(3);
        notificationListRecycler.addOnRefreshListener(new RefreshRecyclerView.OnRefreshListener() {
            @Override
            public void onRefresh() {
                //获取当前选择的科室
                int position = SharedXmlUtil.getInstance().read(CURRENT_POSITION, 0);
                handleResult(typeList.get(position).getMessageType(),typeList.get(position).getTypeName());
            }

            @Override
            public void onLoadMore() {
                loadMore();
            }
        });
        notificationListRecycler.setLayoutManager(new LinearLayoutManager(this));

        //获取全部消息列表
        getAllMessageListHttpRequest();
    }
    //获取全部消息列表
    private void getAllMessageListHttpRequest() {
        currentPageNum = 0;
        SharedXmlUtil xmlUtil = SharedXmlUtil.getInstance();
        HttpUtil.searchMessageList(xmlUtil.getDeviceId(), xmlUtil.getToken(), xmlUtil.getHospitalId(),
                xmlUtil.getUserIdentityId(), xmlUtil.getMessageTag(), currentPageNum, currentNum, -1, new DisposableObserver<SearchMessageListResult>() {
                    @Override
                    public void onNext(SearchMessageListResult searchMessageListResult) {
                        if (searchMessageListResult.getResult().equals(ErrorCodeReturn.success+"")) {
                            SharedXmlUtil.getInstance().setToken(URLDecoderUtil.getDecoder(searchMessageListResult.getData().getToken()));
                            mMessageList = searchMessageListResult.getData().getMessageList();
                            countNum = Integer.parseInt(URLDecoderUtil.getDecoder(searchMessageListResult.getData().getTotalCount()));
                            Log.e(TAG, "onNext: "+countNum );
                            initRecyclerList();

                            if (searchMessageListResult.getData().getMessageList().size() < currentNum || mMessageList.size() >= countNum) {
                                notificationListRecycler.setNoMore(true);
                            } else {
                                notificationListRecycler.loadMoreComplete();
                            }
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        teacherEventProgress.setVisibility(View.GONE);
                    }

                    @Override
                    public void onComplete() {
                        teacherEventProgress.setVisibility(View.GONE);
                    }
                });
    }

    //首次加载recylist
    private void initRecyclerList() {
        messageListAdapter = new MessageListAdapter(this);
        messageListAdapter.setList(mMessageList);
        notificationListRecycler.setAdapter(messageListAdapter);

        messageListAdapter.setOnItemClickListener(new RecyclerBaseAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(int pos) {
                setMessageRead(URLDecoderUtil.getDecoder(mMessageList.get(pos).getMessageContentID()),mMessageList.get(pos));
            }
        });
    }

    //设置消息为已读
    private void setMessageRead(String messageID, final SearchMessageListResult.DataBean.MessageListBean data) {
        SharedXmlUtil xmlUtil = SharedXmlUtil.getInstance();
        HttpUtil.setMessageRead(xmlUtil.getDeviceId(), xmlUtil.getToken(), xmlUtil.getHospitalId(),
                xmlUtil.getUserIdentityId(), messageID, new DisposableObserver<SetMessageReadResult>() {
                    @Override
                    public void onNext(SetMessageReadResult setMessageReadResult) {
                        if (setMessageReadResult.getResult() == ErrorCodeReturn.success) {
                            SharedXmlUtil.getInstance().setToken(URLDecoderUtil.getDecoder(setMessageReadResult.getData().getToken()));
                            data.setMessageReadState("1");
                            messageListAdapter.notifyDataSetChanged();
                        }
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });

    }

    private void loadMore() {
        //获取当前选择的
        int position = SharedXmlUtil.getInstance().read(CURRENT_POSITION, 0);
        int messageType = typeList.get(position).getMessageType();
        currentPageNum++;
        teacherEventProgress.setVisibility(View.VISIBLE);

        SharedXmlUtil xmlUtil = SharedXmlUtil.getInstance();
        HttpUtil.searchMessageList(xmlUtil.getDeviceId(), xmlUtil.getToken(), xmlUtil.getHospitalId(),
                xmlUtil.getUserIdentityId(), xmlUtil.getMessageTag(), currentPageNum, currentNum, messageType, new DisposableObserver<SearchMessageListResult>() {
                    @Override
                    public void onNext(SearchMessageListResult searchMessageListResult) {
                        if (searchMessageListResult.getResult().equals(ErrorCodeReturn.success+"")) {
                            SharedXmlUtil.getInstance().setToken(URLDecoderUtil.getDecoder(searchMessageListResult.getData().getToken()));
                            mMessageList.addAll(searchMessageListResult.getData().getMessageList());
                            messageListAdapter.setList(mMessageList);

                            if (searchMessageListResult.getData().getMessageList().size() < currentNum || mMessageList.size() >= countNum) {
                                notificationListRecycler.setNoMore(true);
                            } else {
                                notificationListRecycler.loadMoreComplete();
                            }
                        }else {
                            notificationListRecycler.loadMoreComplete();

                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        teacherEventProgress.setVisibility(View.GONE);
                        notificationListRecycler.loadMoreComplete();

                    }

                    @Override
                    public void onComplete() {
                        teacherEventProgress.setVisibility(View.GONE);
                    }
                });
    }






    //本地的类型列表数据
    private void initLocalTypeData() {

        //初始化选中数据为0，第一个
        SharedXmlUtil.getInstance().write(CURRENT_POSITION, 0);

        typeList = new ArrayList<>();
        String[] typeName = new String[]{"全部", "实验室预约", "教学行为"};
        int[] type = new int[]{-1, 0, 1};

        for (int i = 0; i < 3; i++) {
            NotificationTypeLocalBean localBean = new NotificationTypeLocalBean();
            localBean.setMessageType(type[i]);
            localBean.setTypeName(typeName[i]);

            typeList.add(localBean);
        }

    }

    private void showMenu() {
        mPopupWindow = new LPopupWindow(this);
        View view = LayoutInflater.from(this).inflate(R.layout.pop_window_message_info, null, false);
        ListView listView = (ListView) view.findViewById(R.id.pop_window_message_listview);

        //       将view添加到popup里面
        mPopupWindow.setContentView(view);
        mPopupWindow.setBackgroundDrawable(new PaintDrawable(Color.WHITE));
        mPopupWindow.setFocusable(true);
        mPopupWindow.setOutsideTouchable(true);

        //获取当前选择的项目
        final int selectPosition = SharedXmlUtil.getInstance().read(CURRENT_POSITION, 0);

        NotificationTypeAdapter typeAdapter = new NotificationTypeAdapter(this, typeList);
        typeAdapter.setCurrentSelectPosition(selectPosition);
        listView.setAdapter(typeAdapter);

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                SharedXmlUtil.getInstance().write(CURRENT_POSITION, position);
                mPopupWindow.dismiss();

                int messageType = typeList.get(position).getMessageType();
                String typeName = typeList.get(position).getTypeName();

                handleResult(messageType, typeName);
            }
        });

        mPopupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                topTitleTagIv.setSelected(false);

                WindowManager.LayoutParams lp = getWindow().getAttributes();
                lp.alpha = 1.0f;
                getWindow().setAttributes(lp);
            }
        });

        //最后显示popupwindow
        if (mPopupWindow.isShowing()) {
            mPopupWindow.dismiss();

        } else {
            topTitleTagIv.setSelected(true);

            //产生背景变暗效果
            WindowManager.LayoutParams lp = getWindow().getAttributes();
            lp.alpha = 0.4f;
            getWindow().setAttributes(lp);
            //         在那个控件下面显示
//            mPopupWindow.showAsDropDown(notificationTopLayout,Gravity.CENTER,0, Gravity.CENTER);
//            mPopupWindow.showAtLocation(notificationTopLayout, Gravity.CENTER_HORIZONTAL,0,0);

            mPopupWindow.getContentView().measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
            int popupWidth = mPopupWindow.getContentView().getMeasuredWidth();
            int popupHeight = mPopupWindow.getContentView().getMeasuredHeight();
            // 设置好参数之后再show
            int[] location = new int[2];
            notificationTopLayout.getLocationOnScreen(location);
            mPopupWindow.showAtLocation(notificationTopLayout, Gravity.NO_GRAVITY, (location[0] + notificationTopLayout.getWidth() / 2) - popupWidth / 2, location[1] + popupHeight);

        }


    }

    /**
     * 根据条件搜索和刷新
     * @param typeId
     * @param selectedName
     */
    private void handleResult(int typeId, String selectedName) {
        topTitleTv.setText(selectedName);
        teacherEventProgress.setVisibility(View.VISIBLE);
        currentPageNum = 0;
        SharedXmlUtil xmlUtil = SharedXmlUtil.getInstance();
        HttpUtil.searchMessageList(xmlUtil.getDeviceId(), xmlUtil.getToken(), xmlUtil.getHospitalId(),
                xmlUtil.getUserIdentityId(), xmlUtil.getMessageTag(), currentPageNum, currentNum, typeId, new DisposableObserver<SearchMessageListResult>() {
                    @Override
                    public void onNext(SearchMessageListResult searchMessageListResult) {
                        if (searchMessageListResult.getResult().equals(ErrorCodeReturn.success+"")) {
                            SharedXmlUtil.getInstance().setToken(URLDecoderUtil.getDecoder(searchMessageListResult.getData().getToken()));
                            mMessageList = searchMessageListResult.getData().getMessageList();
                            messageListAdapter.setList(mMessageList);


                            if (searchMessageListResult.getData().getMessageList().size() < currentNum || mMessageList.size() >= countNum) {
                                notificationListRecycler.refreshComplete();
                                notificationListRecycler.setNoMore(true);
                            } else {
                                notificationListRecycler.refreshComplete();
                                notificationListRecycler.setNoMore(false);
                            }
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        teacherEventProgress.setVisibility(View.GONE);
                        notificationListRecycler.refreshComplete();
                    }

                    @Override
                    public void onComplete() {
                        teacherEventProgress.setVisibility(View.GONE);
                    }
                });

    }



    @Override
    protected int getLayoutId() {
        return R.layout.activity_notification_list;
    }

    @Override
    protected void onNetworkConnected(NetUtils.NetType type) {
        noDataLayout.setNoData(R.string.no_notification_text);
        notificationListRecycler.setEmptyView(noDataLayout);
        getAllMessageListHttpRequest();
    }

    @Override
    protected void onNetworkDisConnected() {
        noDataLayout.setNoNetWork();
        notificationListRecycler.setEmptyView(noDataLayout);
        messageListAdapter.notifyDataSetChanged();
    }

}
